package com.wmz.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.HashSet;

/**
 * @author wmz
 * @date 2024/7/6 10:21
 * @description SwaggerAutoConfiguration
 */
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration {
    @Autowired
    private SwaggerProperties swaggerProperties;
    // 环境对象
    @Autowired
    private Environment environment;

    /**
     * 设置Swagger文档对象
     * 只在开发阶段生成，生产环境不需要生产
     * @return
     */
    @Bean
    public Docket docket() {
        Boolean flag = true;
        //判断当前是否为生产环境
        String[] activeProfiles = environment.getActiveProfiles();
        for (String activeProfile : activeProfiles) {
            if(activeProfile.equals("pro")) {
                flag = false;
                break;
            }
        }
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(getApiInfo())  //文档描述信息对象
                .enable(flag)   //是否生成文档的开关
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))  // 基于包名描述swagger对象
                .build();

    }

    /**
     * 获得swagger文档描述信息
     * @return
     */
    private ApiInfo getApiInfo() {
        Contact contact = new Contact(
                swaggerProperties.getName(),
                swaggerProperties.getUrl(),
                swaggerProperties.getEmail()
        );
        ApiInfo apiInfo = new ApiInfo(
                swaggerProperties.getTitle(),
                swaggerProperties.getDescription(),
                swaggerProperties.getVersion(),
                swaggerProperties.getTremsOfServiceUrl(),
                contact,
                swaggerProperties.getLincense(),
                swaggerProperties.getLincenseUrl(),
                new HashSet<>()
        );
        return apiInfo;
    }
}
